$.namespace('report.scoreCnt');
var ReportData = undefined;
report.scoreCnt = function() {

	return {
		init : function() {
			EasyUIInit.initControl(this.config.toolbar);
			EasyUIInit.initControl(this.config.grid);
			report.scoreCnt.loadData();
		},
		loadData : function() {
			$.ajax({
				type : 'GET',
				url : ctxRest + '/gcb/report/GetFullStruct',
				contentType : 'application/json;charset=UTF-8',
				success : function(data) {
					ReportData = data;
					//初始化总计栏
					ReportData[ReportData.length]={
							gridID:'',
							gridName:'总计：',
							scoreType:'000000',
							scoreTypeName:''
					};
					
					
					var fyear = ($('#fromYear').combobox('getValue'));
					var tyear = ($('#toYear').combobox('getValue'));
					var fmonth = ($('#fromMonth').combobox('getValue'));
					var tmonth = ($('#toMonth').combobox('getValue'));
					//alert(JSON.stringify({paraMap:{fyear:fyear,fmonth:fmonth,tyear:tyear,tmonth:tmonth}}));
					$.ajax({
						type : 'POST',
						data: JSON.stringify({paramMap:{fyear:fyear,fmonth:fmonth,tyear:tyear,tmonth:tmonth}}),
						url : ctxRest+ '/gcb/report/GetScoreCount',
						contentType : 'application/json;charset=UTF-8',
						success : function(data) {
							var mcols = [];
							try { mcols = report.scoreCnt .getMonthArray(); } catch (e) { }
							// 初始化结构
							for (var i = 0; i < ReportData.length; i++) {
								for (var j = 0; j < mcols.length; j++) {
									eval('ReportData[' + i + '].' + mcols[j].field + '=0');
								}
								ReportData[i].average = 0;
								ReportData[i].count = 0;
							}
							for (var i = 0; i < data.length; i++) {
								for (var j = 0; j < ReportData.length; j++) {
									if (ReportData[j].gridID == data[i].gridID && ReportData[j].scoreType == data[i].scoreType) {
										try {
											eval('ReportData['+ j+ '].M'+ data[i].yearMonth+ '='+ data[i].value);
										} catch (e) { }
										break;
									}
								}
							}
							for (var i = 0; i < ReportData.length; i++) {
								for (var j = 0; j < mcols.length; j++) {
									try {
										eval('ReportData[' + i + '].count += ReportData[' + i + '].' + mcols[j].field);
									} catch (e) { }
								}
								if (mcols.length > 0)
									ReportData[i].average =  ReportData[i].count/mcols.length;
								ReportData[i].average = Math.round(ReportData[i].average * 100)/100;
							}
							
							var t1=ReportData[ReportData.length-1];
							var t2=ReportData[ReportData.length-2];
							for (var i = ReportData.length-3; i >=0; i--) {
								if(ReportData[i].scoreType=='999999'){
									t2=ReportData[i];
									continue;
								}
								for (var j = 0; j < mcols.length; j++) {
									try {
										eval('t1.'+mcols[j].field+' += ReportData[' + i + '].' + mcols[j].field);
										eval('t2.'+mcols[j].field+' += ReportData[' + i + '].' + mcols[j].field);
									} catch (e) { }

								}								
								t1.count+=ReportData[i].count;
								t1.average=t1.count/mcols.length;
								t1.average = Math.round(t1.average * 100)/100;										
								
								t2.count+=ReportData[i].count;
								
								t2.average=t2.count/mcols.length;
								t2.average = Math.round(t2.average * 100)/100;
							}
							t1.average=t1.count/mcols.length;
							t1.average = Math.round(t1.average * 100)/100;
 
							var gridcols = report.scoreCnt.getColumns();
							$('#grid').datagrid({
								columns : gridcols,
								data : ReportData
							});
						}
					})
				}
			})
		},
		getMonthArray : function() {

			var fyear = parseInt($('#fromYear').combobox('getValue'));
			var tyear = parseInt($('#toYear').combobox('getValue'));
			var fmonth = parseInt($('#fromMonth').combobox('getValue'));
			var tmonth = parseInt($('#toMonth').combobox('getValue'));

			var cols = [];

			for (var i = 0; (new String()).concat(fyear, (new String()).concat(
					'0', fmonth).substr(-2)) <= (new String()).concat(tyear,
					(new String()).concat('0', tmonth).substr(-2)); i++) {

				cols[i] = {
					title : (new String()).concat(fyear, '年', fmonth, '月'),
					field : (new String()).concat('M', fyear, fmonth),
					width : 30
				};
				if (fmonth < 12) {
					fmonth++
				} else {
					fyear++;
					fmonth = 1;
				}
			}
			return cols;

		},

		getColumns : function() {
			var cols = [ [ {
				title : '广场名称',
				field : 'gridName',
				width : 60
			}, {
				title : '项目名称',
				field : 'scoreTypeName',
				width : 60
			} ] ];

			var mcols = [];
			try {
				mcols = this.getMonthArray();
			} catch (e) {
				;
			}
			for (var i = 0; i < mcols.length; i++)
				cols[0][cols[0].length] = mcols[i];

			cols[0][cols[0].length] = {
				title : '总数',
				field : 'count',
				width : 30
			};
			cols[0][cols[0].length] = {
					title : '平均数',
					field : 'average',
					width : 30
				};

			return cols;
		},
		getYears : function() {
			var years = [];
			for (var i = 0; i < 10; i++) {
				years[i] = {
					id : 2015 + i,
					name : (2015 + i) + '年',
					selected : (new Date()).getFullYear() == (2015 + i)
				}
			}
			return years;
		},
		getMonth : function() {

			var month = [];
			for (var i = 0; i < 12; i++) {
				month[i] = {
					id : i + 1,
					name : (i + 1) + '月份',
					selected : (new Date()).getMonth() == i
				}
			}
			return month;
		}
	}
}();

report.scoreCnt.config = {
	grid : {
		id : "grid",
		type : "easyui-datagrid",
		option : {
			title : '',
			border : false,
			idField : 'id',
			fitColumns : true,
			pagination:false,
			// data:report.scoreCnt.loadData(),
			// columns : report.scoreCnt.getColumns(),
			toolbar : '#toolbar',
			onLoadSuccess : function() {
				$('#grid').datagrid('autoMergeCells', [ 'gridName'  ]);
			}
		}
	},
	toolbar : {
		id : 'toolbar',
		type : 'div',
		isExternal : true,
		controls : [ {
			id : 't1',
			type : 'span',
			isExternal : true,
			InnerHTML : '起始年度：'
		}, {
			id : 'fromYear',
			type : 'easyui-combobox',
			option : {
				width : 80,
				valueField : 'id',
				textField : 'name',
				data : report.scoreCnt.getYears()
			}
		}, {
			id : 't2',
			type : 'span',
			isExternal : true,
			InnerHTML : '月份：'
		}, {
			id : 'fromMonth',
			type : 'easyui-combobox',
			option : {
				width : 80,
				valueField : 'id',
				textField : 'name',
				data : report.scoreCnt.getMonth()
			}
		}, {
			id : 't3',
			type : 'span',
			isExternal : true,
			InnerHTML : '&nbsp;&nbsp;&nbsp;&nbsp;截止年度：'
		}, {
			id : 'toYear',
			type : 'easyui-combobox',
			option : {
				width : 80,
				valueField : 'id',
				textField : 'name',
				data : report.scoreCnt.getYears()
			}
		}, {
			id : 't4',
			type : 'span',
			isExternal : true,
			InnerHTML : '月份：'
		}, {
			id : 'toMonth',
			type : 'easyui-combobox',
			option : {
				width : 80,
				valueField : 'id',
				textField : 'name',
				data : report.scoreCnt.getMonth()
			}
		}, {
			type : 'easyui-linkbutton',
			id : 'btnSearch',
			option : {
				text : '查询',
				iconCls : 'icon-search',
				plain : true,
				onClick : report.scoreCnt.loadData
			}
		} ]
	}
};

$.extend($.fn.datagrid.methods, {
	autoMergeCells : function(jq, fields) {
		return jq.each(function() {
			var target = $(this);
			if (!fields) {
				fields = target.datagrid("getColumnFields");
			}
			var rows = target.datagrid("getRows");
			var i = 0, j = 0, temp = {};
			for (i; i < rows.length; i++) {
				var row = rows[i];
				j = 0;
				for (j; j < fields.length; j++) {
					var field = fields[j];
					var tf = temp[field];
					if (!tf) {
						tf = temp[field] = {};
						tf[row[field]] = [ i ];
					} else {
						var tfv = tf[row[field]];
						if (tfv) {
							tfv.push(i);
						} else {
							tfv = tf[row[field]] = [ i ];
						}
					}
				}
			}

			$.each(temp, function(field, colunm) {
				$.each(colunm, function() {
					var group = this;
					if (group.length > 1) {
						var before, after, megerIndex = group[0];
						for (var i = 0; i < group.length; i++) {
							before = group[i];
							after = group[i + 1];
							if (after && (after - before) == 1) {
								continue;
							}
							var rowspan = before - megerIndex + 1;
							if (rowspan > 1) {
								target.datagrid('mergeCells', {
									index : megerIndex,
									field : field,
									rowspan : rowspan
								});
							}
							if (after && (after - before) != 1) {
								megerIndex = after;
							}
						}
					}
				});
			});
		});
	}
});

$(function() {
	report.scoreCnt.init();
})